package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.*;
import cn.wolfcode.feign.AlipayFeignApi;
import cn.wolfcode.feign.IntergralFeignApi;
import cn.wolfcode.mapper.OrderInfoMapper;
import cn.wolfcode.mapper.PayLogMapper;
import cn.wolfcode.mapper.RefundLogMapper;
import cn.wolfcode.mapper.SeckillProductMapper;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.IdGenerateUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Created by wolfcode-lanxw
 */
@Service
@Slf4j
public class OrderInfoSeviceImpl implements IOrderInfoService {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PayLogMapper payLogMapper;
    @Autowired
    private RefundLogMapper refundLogMapper;
    @Autowired
    private SeckillProductMapper seckillProductMapper;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private AlipayFeignApi alipayFeignApi;
    @Value("${pay.returnUrl}")
    private String returnUrl;
    @Value("${pay.notifyUrl}")
    private String notifyUrl;
    @Autowired
    private IntergralFeignApi intergralFeignApi;

    @Override
    @Transactional
    public String doSeckill(int time, Long seckillId, Long phone) {
        //  6.1 减少真实库存
        int count = seckillProductMapper.decrStock(seckillId);
        if (count == 0){
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        //  6.2 创建订单  并且保存到数据库中
        String orderNo = createOrder(time,seckillId,phone);
        //  6.3 往redis中存数据为重复下单做铺垫
        redisTemplate.opsForSet().add(SeckillRedisKey.SECKILL_ORDER_SET.getRealKey(time+""),phone+":"+seckillId);
        return orderNo;
    }

    @Override
    @Transactional
    public void cancelOrder(OrderMQResult orderMQResult) {
        // 回补真实库存
        seckillProductMapper.incrStock(orderMQResult.getSeckillId());
        // 回补预库存
        seckillProductService.syncRedisStockCount(orderMQResult.getTime(),orderMQResult.getSeckillId());
        // 修改本地标识
        rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderMQResult.getSeckillId());
        // 修改订单状态
        orderInfoMapper.updateCancelStatus(orderMQResult.getOrderNo(),OrderInfo.STATUS_TIMEOUT);
        log.info("超时取消的业务...");
    }

    @Override
    public OrderInfo find(String orderNo) {
        Object objJson = redisTemplate.opsForHash().get(SeckillRedisKey.SECKILL_ORDER_HASH.getRealKey(""), orderNo);
        if (StringUtils.isEmpty(objJson+"")) {
            return null;
        }
        return JSON.parseObject(objJson+"", OrderInfo.class);
    }

    @Override
    public String payOnline(String orderNo, int type) {
        OrderInfo orderInfo = find(orderNo);
        // 远程调用支付完成支付代码
        PayVo payVo = new PayVo();
        payVo.setOutTradeNo(orderNo);
        payVo.setTotalAmount(orderInfo.getSeckillPrice() + "");
        payVo.setBody(orderInfo.getProductName());
        payVo.setSubject(orderInfo.getProductName());
        payVo.setReturnUrl(returnUrl);
        payVo.setNotifyUrl(notifyUrl);
        Result<String> result = alipayFeignApi.payOnline(payVo);

        if (result != null && !result.hasError()) {
            return result.getData();
        }
        return null;
    }

    @Override
    public void paySuccess(Map<String, String> params) {
        String orderNo = params.get("out_trade_no");
        OrderInfo orderInfo = find(orderNo);
        // 支付成功业务逻辑
        // 插入流水记录
        PayLog payLog = new PayLog();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        payLog.setNotifyTime(sdf.format(new Date()));
        payLog.setTradeNo(orderNo);
        payLog.setPayType(PayLog.PAY_TYPE_ONLINE);
        payLog.setTotalAmount(orderInfo.getSeckillPrice() + "");
        payLogMapper.insert(payLog);
        // 修改订单状态
        orderInfoMapper.changePayStatus(orderNo,OrderInfo.STATUS_ACCOUNT_PAID,OrderInfo.PAYTYPE_ONLINE);
    }

    @Override
    public void refundOnline(OrderInfo orderInfo) {
        // 插入流水记录
        RefundLog refundLog = new RefundLog();
        refundLog.setOutTradeNo(orderInfo.getOrderNo());
        refundLog.setRefundAmount(orderInfo.getSeckillPrice() + "");
        refundLog.setRefundTime(new Date());
        refundLog.setRefundType(OrderInfo.PAYTYPE_ONLINE);
        refundLog.setRefundReason("不要了...");
        refundLogMapper.insert(refundLog);
        // 远程调用支付服务进行退款操作
        RefundVo refundVo = new RefundVo();
        refundVo.setOutTradeNo(orderInfo.getOrderNo());
        refundVo.setRefundAmount(orderInfo.getSeckillPrice() + "");
        refundVo.setRefundReason("不要了...");
        // true:表示退款成功 false :表示退款失败
        Result<Boolean> result = alipayFeignApi.refundOnline(refundVo);
        if (result != null && !result.hasError()) {
            if (!result.getData()) {
                throw new BusinessException(SeckillCodeMsg.REFUND_ERROR);
            }
        }
        // 修改订单状态为退款
        int count = orderInfoMapper.changeRefundStatus(orderInfo.getOrderNo(), OrderInfo.STATUS_REFUND);
        if (count == 0) {
            throw new BusinessException(SeckillCodeMsg.REFUND_ERROR);
        }
        // 回补真实库存
        seckillProductMapper.incrStock(orderInfo.getSeckillId());
        // 回补预库存
        seckillProductService.syncRedisStockCount(orderInfo.getSeckillTime(),orderInfo.getSeckillId());
        // 修改本地标识
        rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderInfo.getSeckillId());
    }

    @Override
    @Transactional
    public void payIntergral(String orderNo, int type) {
        OrderInfo orderInfo = find(orderNo);
        // 插入流水记录
        PayLog payLog = new PayLog();
        payLog.setTotalAmount(orderInfo.getIntergral() + "");
        payLog.setPayType(OrderInfo.PAYTYPE_INTERGRAL);
        payLog.setTradeNo(orderNo);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        payLog.setNotifyTime(sdf.format(new Date()));
        payLogMapper.insert(payLog);
        // 远程调用积分服务进行支付
        OperateIntergralVo operateIntergralVo = new OperateIntergralVo();
        operateIntergralVo.setPk(orderNo);
        operateIntergralVo.setValue(orderInfo.getIntergral());
        operateIntergralVo.setUserId(orderInfo.getUserId());
        operateIntergralVo.setInfo(orderInfo.getProductName());

        Result<String> result = intergralFeignApi.decrIntergral(operateIntergralVo);
        if (result == null || result.hasError()) {
            throw new BusinessException(SeckillCodeMsg.INTERGRAL_SERVER_ERROR);
        }
        // 修改订单状态为已支付
        int count = orderInfoMapper.changePayStatus(orderNo, OrderInfo.STATUS_ACCOUNT_PAID, OrderInfo.PAYTYPE_INTERGRAL);
        if (count == 0) {
            throw new BusinessException(SeckillCodeMsg.INTERGRAL_SERVER_ERROR);
        }
    }

    @Override
    @Transactional
    public void refundIntegral(OrderInfo orderInfo) {
        // 插入流水记录
        RefundLog refundLog = new RefundLog();
        refundLog.setOutTradeNo(orderInfo.getOrderNo());
        refundLog.setRefundAmount(orderInfo.getIntergral() + "");
        refundLog.setRefundTime(new Date());
        refundLog.setRefundType(OrderInfo.PAYTYPE_INTERGRAL);
        refundLog.setRefundReason("不要了...");
        refundLogMapper.insert(refundLog);
        // 远程调用积分服务退款
        OperateIntergralVo operateIntergralVo = new OperateIntergralVo();
        operateIntergralVo.setPk(orderInfo.getOrderNo());
        operateIntergralVo.setValue(orderInfo.getIntergral());
        operateIntergralVo.setUserId(orderInfo.getUserId());
        operateIntergralVo.setInfo(orderInfo.getProductName());
        Result<String> result = intergralFeignApi.incrIntergral(operateIntergralVo);
        if (result == null || result.hasError()) {
            throw new BusinessException(SeckillCodeMsg.INTERGRAL_SERVER_ERROR);
        }
        // 修改状态
        int count = orderInfoMapper.changeRefundStatus(orderInfo.getOrderNo(), OrderInfo.STATUS_REFUND);
        if (count == 0) {
            throw new BusinessException(SeckillCodeMsg.INTERGRAL_SERVER_ERROR);
        }
        // 回补真实库存
        seckillProductMapper.incrStock(orderInfo.getSeckillId());
        // 回补预库存
        seckillProductService.syncRedisStockCount(orderInfo.getSeckillTime(),orderInfo.getSeckillId());
        // 修改本地标识
        rocketMQTemplate.sendOneWay(MQConstant.CANCEL_SECKILL_OVER_SIGE_TOPIC,orderInfo.getSeckillId());
    }

    private String createOrder(int time, Long seckillId, Long phone) {
        SeckillProductVo seckillProductVo = seckillProductService.find(time, seckillId);
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setCreateDate(new Date());
        orderInfo.setProductPrice(seckillProductVo.getProductPrice());  //原价
        orderInfo.setDeliveryAddrId(1L);        //地址
        orderInfo.setIntergral(seckillProductVo.getIntergral());    //积分
        orderInfo.setProductCount(1);                               //商品总数
        orderInfo.setProductId(seckillProductVo.getProductId());    //商品ID
        orderInfo.setProductImg(seckillProductVo.getProductImg());  //商品图片
        orderInfo.setProductName(seckillProductVo.getProductName());    //商品名称
        orderInfo.setSeckillDate(new Date());                       //秒杀的日期
        orderInfo.setSeckillId(seckillProductVo.getId());           //秒杀商品ID
        orderInfo.setSeckillPrice(seckillProductVo.getSeckillPrice());  //秒杀价格
        orderInfo.setSeckillTime(time);                             //秒杀场次
        orderInfo.setUserId(phone);                                 //用户ID
        orderInfo.setOrderNo(IdGenerateUtil.get().nextId()+"");     //订单编号
        orderInfoMapper.insert(orderInfo);
        return orderInfo.getOrderNo();
    }
}
